#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask,request
import json
import socket
import threading
from time import sleep
clients = []
def recv (conn,addr):
    print(f'new thread deal {addr} data')
    while True:
        try:
            data = conn.recv(1024).decode("utf-8")
            if len(data)>0 :
                print(data)
            else:
                sleep(0.1)
        except Exception as e:
            print(e)
            conn.close()
            return
    
class srv:
    def lsn():
        global clients
        server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
        server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEPORT,1)
        server.setsockopt(socket.SOL_TCP,socket.TCP_NODELAY,1)
        server.bind(("0.0.0.0",54321))
        server.listen(1024)
        while True:
            sock,addr = server.accept()
            clients = list(filter(lambda x : x._closed==False,clients))
            clients.append(sock)
            threading.Thread(target=recv,args=(sock,addr)).start()
    def run():
        threading.Thread(target=srv.lsn).start()

app = Flask(__name__)

@app.route("/",methods=["GET"])
def hello():
    return "hello world!my tcp server"
def sendto(c,d):
    try:
        if c._closed == False:
            c.send(d)
    except Exception as e:
        print(e)

@app.route("/move",methods=["POST"])
def move():
    data = request.get_data()
    ctrl = json.loads(data)
    for c in clients:
        print(c)
        sendto(c,data)
    return json.dumps(ctrl,ensure_ascii=False) 

@app.route("/turn",methods=["POST"])       
def turn():
    data = request.get_data()
    ctrl = json.loads(data)
    for c in clients:
        print(c)
        sendto(c,data)
    return json.dumps(ctrl,ensure_ascii=False) 
if __name__ == "__main__":
    srv.run()
    app.run(host="0.0.0.0",port=12345,threaded=True,debug=True)
